package cn.edu.nuc.chat.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPServer implements Runnable {
	
	private static volatile boolean flag = true;
	private int port;
	private static ServerSocket server;
	
	//线程池
	private static ExecutorService executorService = Executors.newCachedThreadPool();
	public TCPServer(int port){
		this.port = port;
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		while( !executorService.isShutdown() ){
			try {
				Socket client = server.accept();
				executorService.execute( new Talk(client) );
				
			} catch (IOException e) {
			}
		}
	}
	
	public static void start(int port){
		Thread tcpServer = new Thread( new TCPServer(port) );
		tcpServer.setDaemon( true ); //setDaemon方法把java的线程设置为守护线程，此方法的调用必须在线程启动之前执行。只有在当前jvm中所有的线程都为守护线程时，jvm才会退出。
			//如果创建的线程没有显示调用此方法，这默认为用户线程
		tcpServer.start();
	}
	
	public static void stop(){
		executorService.shutdown();
		flag = false;
		Set<Map.Entry<String, Socket>> entries = Talk.getClients().entrySet();
		for(Map.Entry<String, Socket> entry : entries){
			try {
				entry.getValue().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if( server != null && ! server.isClosed() ){
			try {
				server.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
